﻿$(function () {
    var cardViewThreshold = 580;
    /* Set a locale manually */
    //$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['en-US']);
    loaddata();
    /* Auto adjust the table's view type (table/card) when screen size changes */
    //window.onresize = function () {
    //    $('#table').bootstrapTable('refreshOptions', {
    //        cardView: document.body.clientWidth < cardViewThreshold
    //    });
    //};
});
function reloaddata() {
    //var opt = {
    //    url: "/lxoa/listvacation/"
    //};
    //$('#table').bootstrapTable('refresh', opt);

    $.ajax({
        url: '/lxoa/listapproveexpense/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        success: function (data) {
            //if (data && data.total > 0) {
                $("#table").bootstrapTable('load', data.rows);
            //} else {
            //    //alert('error');
            //}
        }
    })  
}

function loaddata() {
    $.ajax({
        url: '/lxoa/listapproveexpense/',//only show status =1
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },        
        success: function (data) {
            //if (data && data.total>0) {
                binddata(data.rows);
                //$('.columns-right').append('<button class="btn btn-primary" type="button" data-toggle="modal" data-target="#myModal" name="toggle" aria-label="toggle" title=""> 申请 </button>&nbsp;<button class="btn btn-primary" style="margin-left:4px;" type="button" onclick="vacationtj()" name="toggle" aria-label="toggle" title=""> 统计 </button>');
                //$('.columns-right').append('<button class="btn btn-primary" type="button" data-toggle="modal" data-target="#myModal" name="toggle" aria-label="toggle" title=""> 申请 </button>');
                $('.keep-open').hide();
                var uname = $('#usernamespan').html();
                //$("#vac_person").empty().append("<option value='" + uname + "' mail=''>" + uname + "</option>").attr("disabled", "disabled");
                //getuserlist();//order last one load it.

                //alert('success');
            //} else {
            //    //alert('error');
            //}
        }
    })
}

function binddata(datas) {
    var cardViewThreshold = 580;
    $('#table').bootstrapTable({
        cardView: document.body.clientWidth < cardViewThreshold,
        //striped: true,
        search: true,
        pagination: true,
        ageNumber: 1,
        pageSize: 10,
        pageList: [10, 20, 30, 50],
        showColumns: true,
        showToggle: false,
        //showExport: false,
        columns: [{
            title: '序号',
            field: '',
            formatter: function (value, row, index) {
                return index + 1;
            }
        },{
            field: 'applyuser',
            title: '申请人',
            sortable: true
        },{
            field: 'title',
            title: '报销类型',
            sortable: true
        }, 
        {
            field: 'applydate',
            title: '申请日期',
            sortable: true
            },
        {
            field: 'totalprice',
            title: '金额',
            sortable: true
        },
        {
            field: 'remark',
            title: '备注',
            sortable: true
        },
        {
            field: 'approvalstatus',
            title: '状态',
            sortable: true,
            formatter: Formatterstatus
        },
        {
            field: '',
            title: '操作',
            sortable: true,
            formatter: Formatteropration
        }],
        data: datas
    });
}
function Formatterstatus(value, row, index) {
    if (value && value=='1') {
        return ['<span style="color:gren;">已审核<span>'].join("");
    } else {
        return ['已申请'].join("");
    }
}
function Formatteropration(value, row, index) {
    if (row && row.approvalstatus && row.approvalstatus == '1') {
        return [''].join("");
    } else {
        return ["<button class='btn btn-primary' type='button' onclick='applyrow(\"" + row.guid + "\")' name='toggle' title='审批'>审批</button>"].join("");
        //return ['<button class="btn btn-primary" type="button" onclick="applyrow()" name="toggle" title="审批">审批</button>'].join("");
    }
}
function getuserlist() {
    $.ajax({
        url: '/lxoa/getuserlist/',
        type: 'get',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        success: function (data) {
            if (data && data.length > 0) {
                $("#vac_person").empty();
                $("#vac_person2").empty();
                for (var i = 0; i < data.length; i++) {
                    $("#vac_person").append("<option value='" + data[i].USER + "' mail='" + data[i].MAIL + "'>" + data[i].USER + "</option>");
                    $("#vac_person2").append("<option value='" + data[i].USER + "' mail='" + data[i].MAIL + "'>" + data[i].USER + "</option>");
                }
                //alert('success');
            } else {
                //alert('error');
            }
        }
    })
}

function delrow(obj) {
    $(obj).parent().parent().remove();
}
var editguid = '';
var gemeil = '';//applyer email
var gsqr = '';
function applyrow(obj,email) {
    if (obj) {
        $.ajax({
            url: '/lxoa/getlistbyid/',
            type: 'POST',
            dataType: 'json',
            headers: { "X-CSRFToken": getCookie('csrftoken') },
            data: { id: obj },
            success: function (data) {
                if (data && data.rows && data.rows.length > 0) {
                    //send email success clear text
                    editguid = data.rows[0].guid;
                    gemeil = data.rows[0].temp;
                    gsqr = data.rows[0].applyuser;
                    $('#myModal').modal('show');

                    $('#divtype').html(data.rows[0].title);
                    $('#divtotal').html(data.rows[0].totalprice);
                    $('#divapprover').html(data.rows[0].approvaluser.split('$')[0]);
                    $('#divapproveremail').html(data.rows[0].approvaluser.split('$')[1]);
                    $('#divdate').html(data.rows[0].applydate);
                    $('#divremark').html(data.rows[0].remark);
                    //obj.title
                    if (data.rows[0].item && data.rows[0].item.length > 0) {
                        var sub = eval(data.rows[0].item);
                        //if (sub.length != 3) {
                        //    if (sub.length > 3) {
                        //        for (var i = 0; i < sub.length-3; i++) {
                        //            var str = '<tr class="tr_dynamic" data-index="0"><td style=""><select class="selectpicker" name="expense_type" data-style="btn-info"><option value="交通费">交通费</option><option value="住宿费">住宿费</option><option value="其他">其他</option></select></td><td style=""><input type="text" id="" name="txt_price" class="form-control" placeholder="请输入" onkeyup="validatetxt(this)" onblur="validatetxt(this);calctotalprice()" aria-describedby="basic-addon1"></td><td style=""><input type="text" id="" name="txt_description" class="form-control" placeholder="请输入" aria-describedby="basic-addon1"></td><td style=""><button type="button" onclick="delrow(this)" class="close" style="color:red;cursor:pointer;" data-dismiss="modal" aria-hidden="true">×</button></td></tr>';
                        //            $("#expense_items").append(str);
                        //        }
                        //    } else {
                        //    }
                        //}
                        $("#expense_items").html("");
                        if (sub.length > 0) {
                            for (var i = 0; i < sub.length; i++) {
                                var str = '<tr class="tr_dynamic" data-index="0"><td style="">' + sub[i].fields.expensetype + '</td><td style="">' + sub[i].fields.expenseprice + '</td><td style="">' + sub[i].fields.remark+'</td></tr>';
                                $("#expense_items").append(str);
                                //var a = sub[i].fields.expensetype;
                                //var b = sub[i].fields.expenseprice;
                                //var c = sub[i].fields.remark;
                                //$($("select[name='expense_type']")[i]).val(a);
                                //$($("input[name='txt_price']")[i]).val(b);
                                //$($("input[name='txt_description']")[i]).val(c);
                            }
                        }

                    }
                    //$('input').attr("readonly", "readonly").css({ "background-color": "#fff", "border": "0px" });
                    //$('input').attr("readonly", "readonly").css({ "border": "0px" });
                    //$('textarea').attr("readonly", "readonly").css({"border": "0px" });
                    //$('#txt_commons').removeAttr("readonly").css("border:1px solid rgba(0,0,0,.15)");
                    //$('select').attr("disabled", "disabled");

                } else {
                }
            }
        })
    }

}
function addrow() {
    var str = '<tr data-index="0"><td style=""><select class="selectpicker" name="expense_type" data-style="btn-info"><option value="交通费">交通费</option><option value="住宿费">住宿费</option><option value="其他">其他</option></select></td><td style=""><input type="text" id="" name="txt_price" class="form-control" placeholder="请输入" onkeyup="validatetxt(this)" onblur="validatetxt(this);calctotalprice()" aria-describedby="basic-addon1"></td><td style=""><input type="text" id="" name="txt_description" class="form-control" placeholder="请输入" aria-describedby="basic-addon1"></td><td style=""><button type="button" onclick="delrow(this)" class="close" style="color:red;cursor:pointer;" data-dismiss="modal" aria-hidden="true">×</button></td></tr>';
    $("#expense_items").append(str);
}
function validatetxt(obj) {
    $(obj).val($(obj).val().replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, ''));
}
function calctotalprice() {
    var item = $("input[name='txt_price']");
    var total = 0;
    for (var i = 0; i < item.length; i++) {
        if ($(item[i]).val().length > 0 && !isNaN($(item[i]).val())) {
            total += parseFloat($(item[i]).val());
        }
    }
    $('#txt_total').val(total);
}

var gyear = $('#vac_year');
var y = new Date().getFullYear();
gyear.empty();
gyear.append("<option value=''>All</option>");
for (var i = 0; i < 5; i++) {
    var c = (y + i) == y ? "selected='selected'" : "";
    gyear.append("<option " + c + " value='" + (y + i) + "'>" + (y + i) + "年</option>");
}

Date.prototype.addDays = function (day, number) {
    var adjustDate = new Date(day + 24 * 60 * 60 * 1000 * 30 * number)
    //alert("Date" + adjustDate.getFullYear() + "-" + adjustDate.getMonth() + "-" + adjustDate.getDate());
    return adjustDate;
}
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds() //??
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

Date.prototype.addDays2 = function (d) {
    this.setDate(this.getDate() + d);
    return this.Format('yyyy-MM-dd');
};
laydate.render({
    elem: '#txt_date',
    lang: 'zh',
    done: function (value, date, endDate) {
        if (value && value.length > 0) {
            $('#vac_date').attr('style', 'border:1px solid #ccc;');
            var curDate = new Date(value);
            $('#vac_enddate').val(curDate.addDays2(parseFloat($('#vac_interval').val())));
        } else {
            $('#vac_enddate').val('');
        }
    }
});

function submitstatus(types) {
        var json_obj = {
            guid: editguid,
            type: types,
            commons: $('#txt_commons').val()
        }
        var json_str = JSON.stringify(json_obj); 
        $.post("/lxoa/updateexpense/", json_str, function (data) {
            if (data && data.success == '1') {
                $('#myAlert').removeClass('hidden');
                setTimeout(function () {
                        //cleartxt();
                        $('#myModal').modal('hide');
                        $('#myAlert').addClass('hidden');
                         reloaddata();
                         sendmail(types);
                        //$('#table').bootstrapTable('refresh');
                        //loaddata();
                    }, 1000);
            } else {
                $('#myAlerterror').removeClass('hidden');
                    setTimeout(function () {
                        $('#myAlerterror').addClass('hidden');
                    }, 1500);
            }

        }, "json");

    }
function cleartxt() {
    $("input[name='txt_price']").val('');
    $("input[name='txt_description']").val('');
      $('#txt_total').val('');
      $('#txt_date').val('');
      $('#expense_remark').val('');
}

function sendmail(typ) {
    var expense_Approver = $('#divapprover').html();// $('#expense_Approver').find("option:selected").text();
    var expense_Approver_email = $('#divapproveremail').html();// $('#expense_Approver').val();
    var uname = $('#usernamespan').html();
    //var gemeil = '';//applyer email
    //var gsqr = '';
    var contents1 = "报销申请";
    var contents = "你好，" + gsqr + "<br/><br/>你申请的报销已经审批！<br/><br/>谢谢！<br/>" + expense_Approver;
    if (typ==2) {
        contents = "你好，" + gsqr + "<br/><br/>你申请的报销已经驳回！<br/><br/>谢谢！<br/>" + expense_Approver;
    }
    $.ajax({
        url: '/lxoa/sendmailexpense/',
        type: 'POST',
        dataType: 'json',
        headers: { "X-CSRFToken": getCookie('csrftoken') },
        data: { contenttitle: contents1, content: contents, receive: gemeil, types: typ },
        success: function (data) {
            if (data && data.success == '1') {
                //send email success clear text
            } else {
            }
        }
    })
}